/*
 */

package com.railway.news.action;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import org.apache.struts2.ServletActionContext;

import cn.org.rapid_framework.page.Page;

import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;
import com.railway.common.base.BaseStruts2Action;
import com.railway.common.constants.SysConstant;
import com.railway.common.util.CaJosn;
import com.railway.common.util.Json;
import com.railway.common.util.StaticMap;
import com.railway.common.util.StaticMethod;
import com.railway.news.model.Category;
import com.railway.news.model.CategoryUserLink;
import com.railway.news.model.News;
import com.railway.news.service.ICategoryManager;
import com.railway.news.service.INewsManager;
import com.railway.news.util.NewsCfgManager;
import com.railway.news.vo.query.NewsQuery;

/**
 * @author  jiangcheng
 * @version 1.0
 * @since 1.0
 */


public class NewsAction extends BaseStruts2Action implements Preparable,ModelDriven{
	//默认多列排序,example: username desc,createTime asc
	protected static final String DEFAULT_SORT_COLUMNS = null;	
	
	//forward paths
	protected static final String QUERY_JSP = "/admin/news/news/query.jsp";
	protected static final String LIST_JSP= "/admin/news/news/list.jsp";
	protected static final String CHECK_JSP= "/admin/news/news/checklist.jsp";
	protected static final String CREATE_JSP = "/admin/news/news/create.jsp";
	protected static final String EDIT_JSP = "/admin/news/news/edit.jsp";
	protected static final String SHOW_JSP = "/admin/news/news/show.jsp";
	protected static final String TITLE_JSP = "/admin/news/news/title.jsp";
	//redirect paths,startWith: !
	protected static final String LIST_ACTION = "!/news/News/list.do";
	private ICategoryManager categoryManager;
	private INewsManager newsManager;
	private String returnUrl;
	private String pNum;
	private String tNum;
	private News news;
	java.lang.String id = null;
	private String[] items;
	private String param;
	
	public void setParam(String param){
		this.param = param;
	}

	public void prepare() throws Exception {
		if (isNullOrEmptyString(id)) {
			news = new News();
		} else {
			news = (News)newsManager.getById(id);
		}
	}
	
	/** 增加setXXXX()方法,spring就可以通过autowire自动设置对象属性,注意大小写 */
	public void setNewsManager(INewsManager manager) {
		this.newsManager = manager;
	}	
	
	public Object getModel() {
		return news;
	}
	
	public void setId(java.lang.String val) {
		this.id = val;
	}

	public void setItems(String[] items) {
		this.items = items;
	}


	public String listAjax(){
		NewsQuery query = newQuery(NewsQuery.class,DEFAULT_SORT_COLUMNS);
		query.setSortColumns("Create_time DESC");
		Page page = newsManager.findPage(query);
		Map map = new HashMap();
		map.put("total", page.getTotalCount());
		map.put("rows", page.getResult());
		Category cat=new Category();
		if(query.getCatId()!=null&& !"null".equals(query.getCatId()) && !"".equals(query.getCatId())){
			cat = categoryManager.getById(query.getCatId()); 
		}
		map.put("titles", cat.getNames());
		return writeAjaxResponse(Json.toJson(map));
	}
	
		public String listAjaxManage() {


		String current_user_id = (String) this.getRequest().getSession()
		.getAttribute("userId");
		String username= (String) this.getRequest().getSession()
		.getAttribute("username");
		NewsQuery query = newQuery(NewsQuery.class, DEFAULT_SORT_COLUMNS);
		if(!username.equals("admin")){
			query.setFromName(username);
		}
		
		query.setSortColumns("CREATE_TIME desc");
		
		Map map = new HashMap();
		try {
			Page page = newsManager.findPage(query);

			map.put("total", page.getTotalCount());
			map.put("rows", page.getResult());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return writeAjaxResponse(Json.toJson(map));
	}
	/** 保存新增对象 */
	public String save(){
		
		String path = this.getRequest().getContextPath();
		String webctxpath = this.getRequest().getScheme()+"://"+this.getRequest().getServerName()+":"+this.getRequest().getServerPort()+path;
	
		//取当前用户作为发布者
		String current_user_id = (String) this.getRequest().getSession().getAttribute(SysConstant.USER_ID);
		
		news.setFromName(StaticMap.getUserValue(current_user_id));
		news.setAuthorId(current_user_id);
		Date d = new Date(System.currentTimeMillis());
		news.setCreateTime(new java.sql.Timestamp(System.currentTimeMillis()));
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
    //    news.setCreateTimeString(sdf.format(d));
		//对新闻里的相对路径过滤一下
        String temp_context = news.getContentText();

        temp_context = temp_context.replaceAll("src=\"/scripts/", "src=\""+webctxpath+"/scripts/");
        news.setContentText(temp_context);
        newsManager.save(news);
		if(returnUrl!=null && !"".equals(returnUrl)){ 
			try {
				this.getResponse().sendRedirect(returnUrl);
			} catch (IOException e) {
				// TODO Auto-generated catch block
			}
			return returnUrl;
		}else{
			return LIST_ACTION;
		} 
	}
	
	/**保存更新对象*/
	public String update() {
		//这里取一下创建时间
		 
        
		News temp=newsManager.getById(news.getId());
		news.setAuthorId(temp.getAuthorId());
		news.setFromName(temp.getFromName());
		
		if(news.getAuthorId()==null&&news.getAuthorId().equals("")){
			String current_user_id = (String) this.getRequest().getSession().getAttribute(SysConstant.USER_ID);
			news.setFromName(StaticMap.getUserValue(current_user_id));
			news.setAuthorId(current_user_id);
		}
		newsManager.update(this.news);
		if(returnUrl!=null && !"".equals(returnUrl)){ 
			try {
				this.getResponse().sendRedirect(returnUrl);
			} catch (IOException e) {
				// TODO Auto-generated catch block
			}
			return returnUrl;
		}else{
			return LIST_ACTION;
		} 
	}
	public String showNewsHeadImg() {

		return "/admin/news/news/newsheadimg.jsp";
	}
	public String showNewsImg() {

		return "/admin/news/news/newsimg.jsp";
	}
	/**删除对象*/
	public String delete() {
		if(items!=null)
			for(String ids:items){
				String[] idArray = ids.split(",");
				for(String id:idArray){
				    News n = 	newsManager.getById(id);
				    newsManager.removeByIdAndPath(n.getContentHtml(),id);
				}
			}
		if(returnUrl!=null){
			try {
				this.getResponse().sendRedirect(returnUrl);
			} catch (IOException e) {
				// TODO Auto-generated catch block
			}
			return returnUrl;
		}else{
			return LIST_ACTION;
		}
	}
	
	public String remove(){
		if(id!=null){
		    News n = 	newsManager.getById(id);
			newsManager.removeByIdAndPath(n.getContentHtml(),id);
		}
		if(returnUrl!=null){
			try {
				this.getResponse().sendRedirect(returnUrl);
			} catch (IOException e) {
				// TODO Auto-generated catch block
			}
			return returnUrl;
		}else{
			return LIST_ACTION;
		}
	}
	public String getNewsById(){
		String id = this.getRequest().getParameter("id");
		News n = newsManager.getById(id);
		Map m = new HashMap();
		m.put("context", n.getContentText());
		return writeAjaxResponse(Json.toJson(m));
	}
	public String checkNews(){
		String current_user_id = (String) this.getRequest().getSession().getAttribute(SysConstant.USER_ID);
		List catList=new ArrayList();
		String photo="";
		String video="";
		CategoryUserLink culinkquery=new CategoryUserLink();
		culinkquery.setState("C");//C代表审核
		culinkquery.setUserid(current_user_id);
		List<CategoryUserLink> userCateList=categoryManager.getPermitCategoriesByUser(culinkquery);
		if(userCateList!=null){
			for(int i=0;i<userCateList.size();i++){
				CategoryUserLink catlink=userCateList.get(i);
				if(catlink.getId()==null){
					
				}else if(catlink.getCategoryid().equals(SysConstant.CATEGORY_TYPE_PHOTO_MANAGEMENT)){ //如果是图片管理员
					photo="photo";
				}else if(catlink.getCategoryid().equals(SysConstant.CATEGORY_TYPE_VIDEO_MANAGEMENT)){ //如果是视频管理员
					video="video";
				}else{
					Category category=categoryManager.getById(catlink.getCategoryid());
					if(category!=null){
						NewsQuery query=newQuery(NewsQuery.class,DEFAULT_SORT_COLUMNS);
						query.setCatId(catlink.getCategoryid());
						query.setSortColumns(" Create_time DESC");
						Page newsPage=newsManager.findPage(query);
						category.setNewsList(newsPage.getResult());
						catList.add(category);
					}
				}
				
				   
			}
		}
		this.getRequest().setAttribute("photo", photo);
		this.getRequest().setAttribute("video", video);
		this.getRequest().setAttribute("catList", catList);
	    return CHECK_JSP;
	}
	public String getNewsByTitle(){
		String title=this.getRequest().getParameter("title");
		java.util.LinkedHashMap map=new java.util.LinkedHashMap();
		List<News> list=newsManager.findByTitle(title);
		
		//取得新闻按专题分类
		if(list!=null){
			for(int i=0;i<list.size();i++){
				News news=list.get(i);
				//在这里对创建者进行转义 
				news.setAuthorId(news.getAuthorId() == null?"":StaticMap.getUserValue(news.getAuthorId()));
				if(news.getCatId()!=null&&!news.equals("")){
				   String catId=news.getCatId();
				   if(map.get(catId)==null){
					   Category cat=new Category();
					   cat.setId(catId);
					   cat.setNames(news.getCatNames());
					   cat.setCaTypes(news.getCaTypes());
					   if(news.getId()!=null&&!news.getId().equals("")){
						   List<News> newsList=cat.getNewsList();
						   if(newsList==null){
							   newsList=new ArrayList();
						   }
						   if(checkLengh(cat,newsList)){
							   newsList.add(news);
						   }
						   cat.setNewsList(newsList);
					  }
					   
					   map.put(catId, cat);
					   
				   }else{
					   Category cat=(Category)map.get(catId);
					   if(news.getId()!=null&&!news.getId().equals("")){
						   List<News> newsList=cat.getNewsList();
						   if(newsList==null){
							   newsList=new ArrayList();
						   }
						   if(checkLengh(cat,newsList)){
							   newsList.add(news);
						   }  
						   cat.setNewsList(newsList);
					  }
					   map.put(catId, cat);
				   }
				}
			}
		}
		Set<Map.Entry<String, Category>> set = map.entrySet();
		List result=new ArrayList();
		Iterator   it= map.keySet().iterator();  
		while(it.hasNext()){  
			 Category cat=(Category)map.get(it.next()); 
	         result.add(cat); 
		} 
	    this.getRequest().setAttribute("catList", result); 
	    return TITLE_JSP;
	}
	/**
	 * 
	 * @return
	 */
	public String getNewsByTitleAjax(){
		
		String title=this.getRequest().getParameter("title");
		java.util.LinkedHashMap map=new java.util.LinkedHashMap();
		List<News> list=newsManager.findByTitle(title);
		
		//取得新闻按专题分类
		if(list!=null){
			for(int i=0;i<list.size();i++){
				News news=list.get(i);
				
				if(news.getCatId()!=null&&!news.equals("")){
				   String catId=news.getCatId();
				   if(map.get(catId)==null){
					   Category cat=new Category();
					   cat.setId(catId);
					   cat.setNames(news.getCatNames());
					   cat.setCaTypes(news.getCaTypes());
					   if(news.getId()!=null&&!news.getId().equals("")){
						   List<News> newsList=cat.getNewsList();
						   if(newsList==null){
							   newsList=new ArrayList();
						   }
						   if(checkLengh(cat,newsList)){
							   newsList.add(news);
						   } 
						   cat.setNewsList(newsList);
					  }
					   
					   map.put(catId, cat);
					   
				   }else{
					   Category cat=(Category)map.get(catId);
					   if(news.getId()!=null&&!news.getId().equals("")){
						   List<News> newsList=cat.getNewsList();
						   if(newsList==null){
							   newsList=new ArrayList();
						   }
						   if(checkLengh(cat,newsList)){
							   newsList.add(news);
						   }
						   cat.setNewsList(newsList);
					  }
					   map.put(catId, cat);
				   }
				}
			}
		}
		Set<Map.Entry<String, Category>> set = map.entrySet();
		
		StringBuffer result=new StringBuffer();
		result.append("[");
        for (Iterator<Map.Entry<String, Category>> it = set.iterator(); it.hasNext();) {
            Map.Entry<String, Category> entry = (Map.Entry<String, Category>) it.next();
            Category cat=entry.getValue();
            
            result.append(CaJosn.CaToJosn(cat));
            if(it.hasNext()){
            	result.append(",");
            }
        }
        result.append("]");
        return writeAjaxResponse(result.toString());
	  
	}
	public boolean checkLengh(Category ca,List list){
		boolean result=false;
		int len=0;
		if(list!=null){
			len=list.size();
		}else{
			return true;
		}
		if(ca.getCaTypes()!=null&&ca.getCaTypes().equals("TXT")&&tNum!=null){
			if(StaticMethod.null2int(tNum)>len){
				return true;
			}else{
				return false;
			}
		}else if(ca.getCaTypes()!=null&&ca.getCaTypes().equals("IMG")&&pNum!=null){
			if(StaticMethod.null2int(pNum)>len){
				return true;
			}else{
				return false;
			}
		}else if(len<6){
			 return true;
		}else{
			return false;
		}
		 
	}
	/** 执行搜索 */
	public String list() {
		return LIST_JSP;
	}
	/** 查看对象*/
	public String show() {
		return SHOW_JSP;
	}
	
	/** 进入新增页面*/
	public String create() {
		return CREATE_JSP;
	}
	/**进入更新页面*/
	public String edit() {		

 
		return EDIT_JSP;
	}
	
	public String getReturnUrl() {
		return returnUrl;
	}

	public void setReturnUrl(String returnUrl) {
		this.returnUrl = returnUrl;
	}

	public String getPNum() {
		return pNum;
	}

	public void setPNum(String num) {
		pNum = num;
	}

	public String getTNum() {
		return tNum;
	}

	public void setTNum(String num) {
		tNum = num;
	}

	public void setCategoryManager(ICategoryManager categoryManager) {
		this.categoryManager = categoryManager;
	}

}
